package com.hxk.juc;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 票
 */
public class Ticket {

    private int num = 30;

    //jdk5之前处理多线程方式（同步方法）
    public synchronized void sales(){
        if(num > 0){
            System.out.println(Thread.currentThread().getName()+">>>>>卖出了第"+(num--)+"张票，还剩："+num);
        }
    }

    //jdk5之前处理多线程方式（同步代码块）性能优于上面
    public void sales1(){
        synchronized (this) {
            if (num > 0) {
                System.out.println(Thread.currentThread().getName() + ">>>>>卖出了第" + (num--) + "张票，还剩：" + num);
            }
        }
    }

    private Lock lock = new ReentrantLock();
    //jdk5之后处理多线程方式（重锁）性能优于上面
    public void sales2(){
        lock.lock();
        try {
            if (num > 0) {
                System.out.println(Thread.currentThread().getName() + ">>>>>卖出了第" + (num--) + "张票，还剩：" + num);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
          lock.unlock();
        }
    }
}
